﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Dependency;
using Abp.Events.Bus.Exceptions;
using Abp.Events.Bus.Handlers;
using Abp.UI;
using Abp.Web.Mvc.Authorization;
using WanFang.Authorization;
using WanFang.Authorization.Roles;
using WanFang.Users;
using WanFang.Web.Models.Users;
using WanFang.Authorization.Users;
using WanFang.Web.Models.Account;
using Abp.Extensions;
using Microsoft.AspNet.Identity;
using Abp.Domain.Uow;
using Abp.Authorization.Users;
using System.Collections.Generic;
using WanFang.Test;

namespace WanFang.Web.Controllers
{
    [AbpMvcAuthorize]
    public class TestUsersController : WanFangControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly RoleManager _roleManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly UserManager _userManager;

        public TestUsersController(IUserAppService userAppService, RoleManager roleManager,
            IUnitOfWorkManager unitOfWorkManager,
            UserManager userManager)
        {
            _userAppService = userAppService;
            _roleManager = roleManager;
            _unitOfWorkManager = unitOfWorkManager;
            _userManager = userManager;
        }

        [HttpGet]
        public ActionResult Add()
        {

            return View(new RegisterViewModel());
        }


        [HttpPost]
        public ActionResult Add(RegisterViewModel model)
        {
            if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("FormIsNotValidMessage"));
            }
            //Create user
            var user = new User
            {
                Name = model.Name,
                Surname = model.Surname,
                EmailAddress = model.EmailAddress,
                IsActive = true
            };

            user.UserName = model.UserName;
            user.Password = new PasswordHasher().HashPassword(model.Password);

            //Switch to the tenant
            //_unitOfWorkManager.Current.EnableFilter(AbpDataFilters.MayHaveTenant); //TODO: Needed?
            //_unitOfWorkManager.Current.SetTenantId(AbpSession.GetTenantId());

            //Add default roles
            user.Roles = new List<UserRole>();
            foreach (var defaultRole in _roleManager.Roles.Where(r => r.IsDefault).ToList())
            {
                user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
            }

            //Save user
            _userManager.Create(user);
            return Json(new ResultMsg());
        }

        public async Task<ActionResult> Update()
        {
            var user = await _userManager.GetUserByIdAsync(AbpSession.UserId.Value);
            var model = new RegisterViewModel
            {
                Name = user.Name,
                Surname = user.Surname,
                EmailAddress = user.EmailAddress,
                UserName=user.UserName
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult Update(RegisterViewModel model)
        {
            if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("FormIsNotValidMessage"));
            }
            var user = new User
            {
                Name = model.Name,
                Surname = model.Surname,
                EmailAddress = model.EmailAddress,
                IsActive = true
            };
            user.UserName = model.UserName;
            user.Password = new PasswordHasher().HashPassword(model.Password);
            user.Roles = new List<UserRole>();
            foreach (var defaultRole in _roleManager.Roles.Where(r => r.IsDefault).ToList())
            {
                user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
            }
            user.Id = AbpSession.UserId.Value;
            _userManager.Update(user);
            return Json(new ResultMsg());
        }
    }
}